<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户名称" prop="kh">
        <el-input
          v-model="queryParams.kh"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="总部编号" prop="zbbh">
        <el-input
          v-model="queryParams.zbbh"
          placeholder="请输入总部编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址" prop="dz">
        <el-input
          v-model="queryParams.dz"
          placeholder="请输入地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮寄商品" prop="yjsp">
        <el-select v-model="queryParams.yjsp" style="width: 100%;" placeholder="请选择邮寄商品">
          <el-option
            v-for="item in yjwpList"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="快递公司" prop="kdgs">
        <el-select v-model="queryParams.kdgs" style="width: 100%;" placeholder="请选择快递公司">
          <el-option
            v-for="item in yjkdList"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="快递号" prop="kdh">
        <el-input
          v-model="queryParams.kdh"
          placeholder="请输入快递号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="bz">
        <el-input
          v-model="queryParams.bz"
          placeholder="请输入备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="wgbh">
        <el-date-picker
          v-model="querySj"
          @change="selectTime"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="送回取回状态" label-width="110px">
        <el-checkbox-group v-model="shqhzt" size="mini" @change="selectShqhzt">
          <el-checkbox label="1" border>是</el-checkbox>
          <el-checkbox label="0" border>否</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-row style="margin-bottom: 15px">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-form-item label="日期">
          <el-checkbox-group v-model="rq" size="mini" @change="selectRq">
            <el-checkbox label="zt" border>昨天</el-checkbox>
            <el-checkbox label="jt" border>今天</el-checkbox>
            <el-checkbox label="mt" border>明天</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="邮寄状态">
          <el-checkbox-group v-model="yjzt" size="mini" @change="selectYjzt">
            <el-checkbox label="1" border>邮寄</el-checkbox>
            <el-checkbox label="2" border>未邮寄</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="送回">
          <el-checkbox-group v-model="shzt" size="mini" @change="selectShtz">
            <el-checkbox label="bksh" border>不查看送回</el-checkbox>
            <el-checkbox label="zksh" border>只查看送回</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="取回">
          <el-checkbox-group v-model="qhzt" size="mini" @change="selectQhtz">
            <el-checkbox label="bkqh" border>不查看取回</el-checkbox>
            <el-checkbox label="zkqh" border>只查看取回</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdateData"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDeleteData"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >全部导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-download"
          size="mini"
          :disabled="multiple"
          @click="handleSelectExport"
        >导出选择数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-refresh-right"
          size="mini"
          @click="syncData"
        >批量同步完工单</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="mailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="完工单号" width="120" align="left" prop="wgbh">
        <template slot-scope="scope">
          <div style="color: #00afff;cursor: pointer;">
            <span @click="showInfo(scope.row)"> {{scope.row.wgbb}}</span> &nbsp;
            <el-link v-if="scope.row.wgbb !== null && scope.row.wgbb !== '' && scope.row.wgbb !== undefined"
                     :underline="false"
                     type="success"
                     @click="copyText(scope.row.wgbb)"
                     icon="el-icon-copy-document"
                     style="font-size: 10px"></el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="客户编号" width="80" align="left" prop="bh" />
      <el-table-column label="客户" align="left" width="250" prop="kh">
        <template slot-scope="scope">
          <div style="cursor: pointer;">
            <span> {{scope.row.kh}}</span> &nbsp;
            <el-link v-if="scope.row.kh !== null && scope.row.kh !== '' && scope.row.kh !== undefined"
                     :underline="false"
                     type="success"
                     @click="copyText(scope.row.kh)"
                     icon="el-icon-copy-document"
                     style="font-size: 10px"></el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="地址" align="left" width="300" prop="dz">
        <template slot-scope="scope">
          <div style="cursor: pointer;">
            <span> {{scope.row.dz}}</span> &nbsp;
            <el-link v-if="scope.row.dz !== null && scope.row.dz !== '' && scope.row.dz !== undefined"
                     :underline="false"
                     type="success"
                     @click="copyText(scope.row.dz)"
                     icon="el-icon-copy-document"
                     style="font-size: 10px"></el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="邮寄商品" width="75" align="left" prop="yjsp">
        <template slot-scope="scope">
          <span>{{yjwpList.filter(item => item.dictValue === scope.row.yjsp)[0] !== undefined ? yjwpList.filter(item => item.dictValue === scope.row.yjsp)[0].dictLabel : ""}}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" width="50" align="center" prop="number" />
      <el-table-column label="快递公司" width="80" align="left" prop="kdgs">
        <template slot-scope="scope">
          <span v-if="scope.row.kdgs === 'sh' || scope.row.kdgs === 'qh'" style="color: #F56C6C">{{yjkdList.filter(item => item.dictValue === scope.row.kdgs)[0] !== undefined ? yjkdList.filter(item => item.dictValue === scope.row.kdgs)[0].dictLabel : ""}}</span>
          <span v-else>{{yjkdList.filter(item => item.dictValue === scope.row.kdgs)[0] !== undefined ? yjkdList.filter(item => item.dictValue === scope.row.kdgs)[0].dictLabel : ""}}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮寄日期" width="100" align="center" prop="yjsj" />
      <el-table-column label="邮寄状态" width="80" align="left" prop="yjzt">
        <template slot-scope="scope">
          <span v-if="scope.row.yjzt === '1'"><el-tag type="success">邮寄</el-tag></span>
          <span v-if="scope.row.yjzt === '2'"><el-tag type="warning">未邮寄</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="left" prop="bz" show-overflow-tooltip>
        <template slot-scope="scope">
          <span style="color: #F56C6C">{{scope.row.bz}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改快递邮寄对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="85%" @close="cancel" append-to-body close-on-press-escape>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="完工编号" prop="wgbb">
              <el-input v-model="form.wgbb" placeholder="请输入完工编号" />
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="总部编号" prop="zbbh">-->
<!--              <el-input v-model="form.zbbh" placeholder="请输入总部编号" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="邮寄商品" prop="yjsp">
              <el-select v-model="form.yjsp" style="width: 100%;" placeholder="请选择邮寄商品">
                <el-option
                  v-for="item in yjwpList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户" prop="kh">
              <el-input v-model="form.kh" placeholder="请选择客户">
                <el-button type="primary" slot="prepend" @click.native="selectUser"> 选择客户 </el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="number">
              <el-input v-model="form.number" type="number" placeholder="请输入数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="地址" prop="dz">
              <el-input type="textarea" v-model="form.dz" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="快递公司" prop="kdgs">
              <el-select v-model="form.kdgs" style="width: 100%;" placeholder="请选择快递公司">
                <el-option
                  v-for="item in yjkdList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="邮寄状态" prop="yjzt">
              <el-radio-group v-model="form.yjzt">
                <el-radio v-for="item in yjztList" :label="item.dictValue" border>{{item.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="form.kdgs === 'sh' || form.kdgs === 'qh'">
            <el-form-item label="送回/取回状态" prop="shqhzt">
              <el-radio-group v-model="form.shqhzt">
                <el-radio v-for="item in sfList" :label="item.dictValue" border>{{item.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="送回/取回人员">
              <el-input v-model="form.shqhyh" readonly placeholder="请选择送回/取回人员">
                <el-button style="background-color: #92C3FE;color: black" type="primary" slot="prepend" @click.native="selectRy"> 选择人员 </el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="快递号" prop="kdh">
              <el-input v-model="form.kdh" placeholder="请输入快递号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="邮寄日期">
              <el-date-picker clearable
                              style="width: 100%"
                              v-model="form.yjsj"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择邮寄日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="bz">
              <el-input
                maxlength="1000"
                :autosize="{ minRows: 3, maxRows: 4 }"
                show-word-limit
                v-model="form.bz"
                type="textarea"
                placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <BhList v-if="showYwd" :showBh="showYwd" @closeDialog="closeDialog" @selectData="selectData"></BhList>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="ShowBtn" :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <khList v-if="showUser" :showUser="showUser" @selectData="selectKhData" @closeDialog="closeUserDialog"></khList>
    <UserSelectModal v-if="showUserDialog" :showUserDialog="showUserDialog" @close="closeUser" @selectUser="resultUser"></UserSelectModal>
  </div>
</template>

<script>
import UserSelectModal from '@/views/components/user/UserSelectModal.vue'
import khList from "@/views/gd/ywd/khList.vue";
import { listMail, getMail, delMail, addMail, updateMail, syncStatusZt } from "@/api/gd/mail";
import BhList from '@/views/gd/wgd/BhList.vue'
import { parseTime } from '@/utils/ruoyi'
export default {
  name: "Mail",
  components: { BhList, khList, UserSelectModal },
  watch: {
    '$route': {
      immediate: true,
      async handler(route) {
        if (route.query.sy === "true") {
          await this.resetQueryData()
          this.queryParams.shqhzt = '0'
          this.queryParams.kdgs = 'sh,qh'
          this.sy = true
          this.getList()
        }
      },
      deep: true
    },
  },
  data() {
    return {
      showUserDialog: false,
      ryData: {},
      rq: [],
      yjzt: [],
      shzt: [],
      qhzt: [],
      shqhzt: [],
      showUser: false,
      querySj: [],
      userName: this.$store.getters.name,
      showYwd: false,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 快递邮寄表格数据
      mailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      ShowBtn: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        zbbh: undefined,
        khid: undefined,
        kh: undefined,
        dz: undefined,
        yjsp: undefined,
        number: undefined,
        kdgs: undefined,
        kdh: undefined,
        bz: undefined,
        yjzt: undefined,
        sh: undefined,
        qh: undefined,
        params: {
          startTime: '',
          endTime: ''
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        khid: [
          { required: true, message: "客户id不能为空", trigger: "blur" }
        ],
        kh: [
          { required: true, message: "客户不能为空", trigger: "change" }
        ],
        dz: [
          { required: true, message: "地址不能为空", trigger: "change" }
        ],
        yjsp: [
          { required: true, message: "邮寄商品不能为空", trigger: "blur" }
        ],
        yjzt: [
          { required: true, message: "请选择邮寄状态", trigger: "blur" }
        ],
        number: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        kdgs: [
          { required: true, message: "快递公司不能为空", trigger: "blur" }
        ],
        wgbb: [
          { required: true, message: "完工编号不能为空", trigger: "blur" }
        ]
      },
      yjwpList: [],
      yjztList: [],
      yjkdList: [],
      sfList: [],
      sy: false
    };
  },
  created() {
    console.log("this.sy", this.sy)
    if (!this.sy) {
      this.getList();
    }
    this.getDict()
  },
  methods: {
    selectRy() {
      this.ryData = this.form
      this.showUserDialog = true
    },
    closeUser() {
      this.ryData = {}
      this.showUserDialog = false
    },
    resultUser(user) {
      let ids = user.map(item => item.userId)
      let names = user.map(item => item.nickName)
      // 判断当前选择的是下场负责人还是下场人员
      this.$set(this.form, 'shqhyh', names.toString())
      this.$set(this.form, 'shqhyhid', ids.toString())
      this.closeUser()
    },
    selectKhData(row) {
      this.$set(this.form, 'kh', row.khname)
      this.$set(this.form, 'khid', row.id)
      this.$set(this.form, 'dz', row.dz)
      this.$set(this.form, 'bh', row.bh)
      this.closeUserDialog()
    },
    closeUserDialog() {
      this.showUser = false
    },
    selectUser() {
      this.showUser = true
    },
    selectTime(time) {
      this.queryParams.params.startTime = time[0]
      this.queryParams.params.endTime = time[1]
    },
    copyText(data) {
      const textarea = document.createElement('textarea');
      textarea.value = data;
      document.body.appendChild(textarea);
      textarea.select();
      try {
        // 尝试执行复制操作
        const success = document.execCommand('copy');
        if (success) {
          this.$message.success("已复制！")
        } else {
          this.$message.error("复制失败！")
        }
      } catch (error) {
        this.$message.error("复制失败！")
      }
      document.body.removeChild(textarea);
    },
    showInfo(row) {
      getMail(row.id).then(response => {
        this.form = response.data
        this.open = true
        this.ShowBtn = false
        this.title = "业务单信息";
      })

    },
    selectData(row, data) {
      this.$set(this.form, 'khid', row.id)
      this.$set(this.form, 'kh', row.khname)
      this.$set(this.form, 'zbbh', row.zbbh)
      this.$set(this.form, 'dz', row.dz)
      this.$set(this.form, 'bh', row.bh)
      this.showYwd = false
    },
    closeDialog() {
      this.showYwd = false
    },
    selectNumber() {
      this.showYwd = true
    },
    getDict() {
      this.getDicts("maill_goods").then(res => {
        this.yjwpList = res.data
      })
      this.getDicts("maill_yjzt").then(res => {
        this.yjztList = res.data
      })
      this.getDicts("maill_kd").then(res => {
        this.yjkdList = res.data
      })
      this.getDicts("gd_sf").then(res => {
        this.sfList = res.data
      })
    },
    /** 查询快递邮寄列表 */
    getList() {
      this.loading = true;
      listMail(this.queryParams).then(response => {
        this.mailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.ShowBtn = false
      this.reset();
      this.getList()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        zbbh: undefined,
        khid: undefined,
        kh: undefined,
        dz: undefined,
        yjsp: undefined,
        number: undefined,
        kdgs: undefined,
        kdh: undefined,
        bz: undefined,
        createBy: this.$store.getters.nickName,
        createTime: parseTime(new Date()),
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        yjsj: new Date()
      };
      this.resetForm("form");
    },
    selectYjzt(item) {
      this.queryParams.yjzt = item.toString()
      this.getList()
    },
    selectShtz(item) {
      this.queryParams.sh = item.toString()
      this.getList()
    },
    selectQhtz(item) {
      this.queryParams.qh = item.toString()
      this.getList()
    },
    selectShqhzt(item) {
      this.queryParams.shqhzt = item.toString()
      this.getList()
    },
    selectRq(item) {
      if (item.length > 0) {
        let hasZt = item.some(item => item === 'zt');
        let hasJt = item.some(item => item === 'jt');
        let hasMt = item.some(item => item === 'mt');
        // ===== 获取昨天日期
        let date = new Date()
        const yesterday = new Date(date);
        yesterday.setDate(yesterday.getDate() - 1); // 减去一天得到昨天的日期
        let zt = this.formatDate(yesterday);
        // ==== 获取今天日期
        let jt = this.formatDate(date);
        // ==== 获取明天
        const tomorrow = new Date(date);
        tomorrow.setDate(tomorrow.getDate() + 1); // 加上一天得到明天的日期
        let mt = this.formatDate(tomorrow);
        // 判断昨天和今天是否已经勾选
        if ((hasZt && hasJt && hasMt) || (hasZt && hasMt)) {  // 昨天 今天 明天
          this.queryParams.params.startTime = zt + " 00:00:00"
          this.queryParams.params.endTime = mt + " 23:59:59"
        }else if (hasZt && hasJt) {  // 昨天 今天
          this.queryParams.params.startTime = zt + " 00:00:00"
          this.queryParams.params.endTime = jt + " 23:59:59"
        }else if(hasJt && hasMt) {  // 今天 明天
          this.queryParams.params.startTime = jt + " 00:00:00"
          this.queryParams.params.endTime = mt + " 23:59:59"
        } else if (hasZt) {  // 昨天
          // 如果只有昨天
          this.queryParams.params.startTime = zt + " 00:00:00"
          this.queryParams.params.endTime = zt + " 23:59:59"
        }else if (hasJt) {  // 今天
          this.queryParams.params.startTime = jt + " 00:00:00"
          this.queryParams.params.endTime = jt + " 23:59:59"
        }else if (hasMt) {  // 明天
          this.queryParams.params.startTime = mt + " 00:00:00"
          this.queryParams.params.endTime = mt + " 23:59:59"
        }
      }else {
        this.queryParams.params.startTime = ""
        this.queryParams.params.endTime = ""
      }
      this.getList()
    },
    selectDay(item) {
      // 1.昨天 2.今天 3.明天
      let date = new Date()
      if (item === 1) {
        const yesterday = new Date(date);
        yesterday.setDate(yesterday.getDate() - 1); // 减去一天得到昨天的日期
        let zt = this.formatDate(yesterday);
        this.queryParams.params.startTime = zt
        this.queryParams.params.endTime = zt
      }else if (item === 2){
        let jt = this.formatDate(date);
        this.queryParams.params.startTime = jt
        this.queryParams.params.endTime = jt
      }else if (item === 3) {
        const tomorrow = new Date(date);
        tomorrow.setDate(tomorrow.getDate() + 1); // 加上一天得到明天的日期
        let mt = this.formatDate(tomorrow);
        this.queryParams.params.startTime = mt
        this.queryParams.params.endTime = mt
      }
      this.getList()
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以加1
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 判断当前的条件是否有开始和结束时间
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams =  {
        pageNum: 1,
        zbbh: undefined,
        khid: undefined,
        kh: undefined,
        dz: undefined,
        yjsp: undefined,
        number: undefined,
        kdgs: undefined,
        kdh: undefined,
        bz: undefined,
        params: {
          startTime: '',
          endTime: ''
        }
      }
      this.querySj = []
      this.yjzt = []
      this.shzt = []
      this.shqhzt = []
      this.rq = []
      this.qhzt = []
      this.handleQuery();
    },
    resetQueryData() {
      this.resetForm("queryForm");
      this.queryParams =  {
        pageNum: 1,
        pageSize: 10,
        zbbh: undefined,
        khid: undefined,
        kh: undefined,
        dz: undefined,
        yjsp: undefined,
        number: undefined,
        kdgs: undefined,
        kdh: undefined,
        bz: undefined,
        params: {
          startTime: '',
          endTime: ''
        }
      }
      this.querySj = []
      this.yjzt = []
      this.shzt = []
      this.shqhzt = []
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.$set(this.form, 'yjzt', '1')
      this.$set(this.form, 'shqhzt', '0')
      this.open = true;
      this.ShowBtn = true
      this.title = "添加快递邮寄";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getMail(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.ShowBtn = true
        this.title = "修改快递邮寄";
      });
    },
    handleUpdateData() {
      this.loading = true;
      this.reset();
      const ids =  this.ids
      getMail(ids).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.ShowBtn = true
        this.title = "修改快递邮寄";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateMail(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addMail(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$modal.confirm('请确认是否删除 总部编号为：' + row.zbbh + ' 客户名称为：' + row.kh + ' 的数据?').then(() => {
        this.loading = true;
        return delMail(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    handleDeleteData() {
      const ids = this.ids;
      const data = this.mailList.filter(item => ids.some(id => id === item.id))
      let delData = data.filter(item => item.status === '0')
      if (delData.length > 0 && this.userName !== 'admin') {
        let obj = ""
        delData.forEach((item, index) => {
          if (index === delData.length-1) {
            obj += "总部编号为：" + item.zbbh + " 客户为： " + item.kh
          }else {
            obj += "总部编号为："  + item.zbbh + " 客户为： " + item.kh + "， "
          }
        })
        this.$message.error("您无权限删除 " + obj + " 数据")
      }else {
        let obj = ""
        data.forEach((item, index) => {
          if (index === data.length-1) {
            obj += "总部编号为：" + item.zbbh + " 客户为： " + item.kh
          }else {
            obj += "总部编号为："  + item.zbbh + " 客户为： " + item.kh + "， "
          }
        })
        this.$modal.confirm('请确认是否删除 ' + obj + ' 的数据?').then(() => {
          this.loading = true;
          return delMail(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        }).finally(() => {
          this.loading = false;
        });
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      let name = this.getTodayDate()
      this.download('gd/mail/export', {
        ...this.queryParams
      }, `${name}_邮寄清单.xlsx`)
    },
    handleSelectExport() {
      const ids = this.ids;
      let name = this.getTodayDate()
      this.download('gd/mail/exportSelectDat/' + ids, {
        ...this.queryParams
      }, `${name} 邮寄订单_${new Date().getTime()}.xlsx`)
    },
    getTodayDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = ('0' + (date.getMonth() + 1)).slice(-2);
      const day = ('0' + date.getDate()).slice(-2);
      return `${year}${month}${day}`;
    },
    syncData() {
      this.$modal.confirm('请确认是否要同步 邮寄状态 到完工单').then(() => {
        this.loading = true;
        syncStatusZt(this.queryParams).then(res => {
          if (res.data) {
            this.$message.success("修改成功！")
          }else {
            this.$message.error("修改失败！")
          }
        })
      }).finally(() => {
        this.loading = false;
        this.getList();
      });
    }
  }
};
</script>
<style scoped>
.el-radio {
  margin-right: 0px;
}
.el-checkbox {
  margin-right: 0px;
}
</style>
